import React, {
	Component,
	useState,
	useEffect,
	useRef
} from "react";
import {
	Text,
	TextInput,
	TouchableOpacity,
	View
} from "react-native";
import CheckBox from 'react-native-check-box';
import Content from "../../components/content/content"
import styles from "./login-sheet";
import * as api from "../../api";
import cache from "../../cache";
import * as config from "../../config";
import * as platform from "../../platform";

// Login.navigationOptions = {
// 	headerRight: (
// 		<View style={{paddingRight:20}} >
// 			<Button onPress={()=>{
// 					alert('this is a button')
// 				}} title='info' color='#000' />
// 		</View>
// 	)
// }

export default function Login(props) {
	const [cellphone, setCellphone] = useState("");
	const [check, setCheck] = useState(false);

	const getCellphone = value => {
		setCellphone(value);
	};
	const [password, setPassword] = useState("");
	const getPassword = value => {
		setPassword(value);
	};

	const login = () => {
		if (password === "" || cellphone === "") {
			global.showToast("账号或密码不能为空");
			return;
		}
		global.showLoading();
		api.login({
			password,
			cellphone,
			device_id: platform.uniqueID,
		}).then(async res => {
			await cache.set(config.TOKENKEY, res.token);
			if (check) {
				cache.set(config.ACCOUNT, cellphone);
				cache.set(config.PASSWORD, password);
			} else {
				cache.delete(config.ACCOUNT);
				cache.delete(config.PASSWORD);
			}
			props.navigation.replace('Tab');
		}).catch(rej => {
			global.showToast(rej);
		}).finally(() => {
			global.closeLoading();
		});
	};

	useEffect(() => {
		cache.get(config.ACCOUNT).then((res) => {
			setCellphone(res);
			setCheck(true);
		});
		cache.get(config.PASSWORD).then((res) => {
			setPassword(res);
		});
	}, []);

	return (
		<Content>
			<View style={styles.content}>
				<View style={styles.input}>
					<View style={styles.inputTitle}>
						<Text>账号:   </Text>
					</View>
					<View style={styles.inputText}>
						<TextInput maxLength={32} 
						 	autoCapitalize="none" 
						 	placeholder="请输入账号" 
						 	style={styles.inputTextC}
						 	onChangeText={getCellphone}
						 	defaultValue={cellphone}
						/>
					</View>
				</View>

				<View style={[styles.input, styles.marginTop20]}>
					<View style={styles.inputTitle}>
						<Text>密码:   </Text>
					</View>
					<View style={styles.inputText}>
						<TextInput maxLength={32} 
							autoCapitalize="none" 
							secureTextEntry={true} 
							placeholder="请输入密码" 
							style={styles.inputTextC}
							onChangeText={getPassword}
							defaultValue={password}
						/>
					</View>
				</View>
				
				<CheckBox
			    style={styles.check}
			    onClick={()=>{
			      setCheck(!check);
			    }}
			    isChecked={check}
			    rightText={"记住密码"}
				/>

				<View style={styles.marginTop20}>
					<TouchableOpacity onPress={login} style={styles.button}>
						<Text style={styles.buttonText}>登录</Text>
					</TouchableOpacity>
				</View>
			</View>
		</Content>
	)
}